#BEGIN
#name=wol
#nead=
#END

apt-get install ethtool -y || exit -1

#Permet a read de lire les \t en debut de ligne
IFS=" "

tmp_file="interfaces.tmp"
file="/etc/network/interfaces"

if (!(test -f "$file.old")) ; then
	cp "$file" "$file.old"
fi

sed -i "s/.*eth0$/auto eth0/" $file
sed -i "s/\(^iface eth0\).*/\1 inet dhcp/" $file

s1="post-up"
r1="post-up /sbin/ethtool -s \$IFACE wol g"

s2="post-down"
r2="post-down /sbin/ethtool -s \$IFACE wol g"

in='0';ok='0';ok1='0';ok2='0';

rm -rf "$tmp_file"
{ while read line ; do
	t1=`echo "$line" | grep iface`
	t2=`echo "$line" | egrep "^auto"`
	#echo "#1#:$t"
	if [ "$t1" != "" ] || [ "$t2" != "" ] ; then
		t=`echo "$line" | grep eth0`
		#echo "#2#$t"
		if [ "$t" != "" ] ; then
			ok="1"
			in="1"
		else
			ok="0"
		fi
	fi
	if [ "$in" == "1" ] && [ "$ok" == 0 ] ; then
		if [ "$ok1" != "1" ] ; then
			echo "$r1" >> $tmp_file
			ok1="1"
		elif [ "$ok2" != "1" ] ; then
			echo "$r2" >> $tmp_file
			ok2="1"
		fi
	fi
	if [ "$ok" == "1" ] ; then
		t1=`echo "$line" | grep $s1`
		t2=`echo "$line" | grep $s2`
		if [ "$t1" != "" ] ; then
			echo "$r1" >> $tmp_file
			ok1="1"
		elif [ "$t2" != "" ] ; then
			echo "$r2" >> $tmp_file
			ok2="1"
		else
			echo "$line" >> $tmp_file 
		fi
	else
		echo "$line" >> $tmp_file
	fi
done } < $file

if [ "$ok1" != "1" ] ; then
	echo "$r1" >> $tmp_file
	ok1="1"
elif [ "$ok2" != "1" ] ; then
	echo "$r2" >> $tmp_file
	ok2="1"
fi

cp "$tmp_file" "$file"


file="/etc/init.d/halt"
tmp_file="halt.tmp"
rm -rf "$tmp_file"
sed -i "s/^\(NETDOWN=\).*$/\1no/" $file
t=`cat $file | egrep "^NETDOWN="`
if [ "$t" == "" ] ; then
	if ( ! ( test -f "$file.old" ) ) ; then
		cp "$file" "file.old"
	fi
	{ while read line ; do
		t=`echo "$line" | egrep "^### END INIT INFO"`
		echo -e "$line" >> $tmp_file
		if [ "$t" != "" ] ; then
			echo "NETDOWN=no" >> $tmp_file
		fi
	done } < $file
	cp $tmp_file $file
fi


